import React, { useState } from 'react';
// import { useNavigate } from 'react-router-dom';
import type { ApiResponse } from '../utils/axios.ts'
import service from '../utils/axios';
import { useAuthStore } from '../zus';
// import { showToast } from 'vant';
import { message } from 'antd';
const Login: React.FC = () => {
  const [name,setname]=useState<string>('')
  const [password,setpassword]=useState<string>('')
  const {setmenu}=useAuthStore()
  // const navigate = useNavigate();
  const goLogin = async(): Promise<void> => {
    // console.log(12312313123);
    
    let res=await service.post('/WYQ/login',{name:name,password:password}) as ApiResponse
    console.log(res);
    
    if(res.code==200){
      setmenu(res.menu||[])
      localStorage.setItem('user', JSON.stringify(res.user)); // 新增，存储用户信息
      message.success('登陆成功',()=>{
        localStorage.setItem('token',res.token||'');
        localStorage.setItem('name',name)
        // localStorage.setItem('lastLogin',name)
        window.location.href='/'
      })
    }else if(res.code==400){
      message.error('用户名或者密码错误')
    }else if(res.code==500){
      message.error('服务器端错误,请联系客服')
    }

    localStorage.setItem('menu',JSON.stringify(res.data.menu))
  };

  return (
    <div className="login-container">
      <h1>系统登录</h1>
      <div className="login-form">
        <div className="form-group">
          <label htmlFor="username">用户名</label>
          <input type="text" id="username" placeholder="请输入用户名" value={name} onChange={(e)=>{setname(e.target.value)}}/>
        </div>
        <div className="form-group">
          <label htmlFor="password">密码</label>
          <input type="password" id="password" placeholder="请输入密码" 
          value={password} onChange={(e)=>{setpassword(e.target.value)}}/>
        </div>
        <button className="btn btn-login" onClick={goLogin}>登录</button>
      </div>
    </div>
  );
};

export default Login; 